<template>
    <div class="remote-list-wrapper">
        <div class="remote-list-title">机器列表</div>
        <div class="remote-block status-1" :class="`${_current_remote_id == 'local' ? 'selected' : ''}`" @click="onClickLocal()">
            <div class="remote-block-header">
                <div class="remote-block-title">本地机器</div>
            </div>
            <div class="remote-block-host">127.0.0.1:3000</div>
        </div>
        <div
            v-for="(remote, index) in _remote_list"
            :key="remote.id"
            class="remote-block"
            :class="`status-${remote.ssh_status} ${_current_remote_id == remote.id ? 'selected' : ''}`"
            @click="onClickRemote(remote)"
        >
            <div class="remote-block-header">
                <div class="remote-block-title">远程： {{ remote.name }}</div>
                <div class="remote-block-toolbar">
                    <el-dropdown trigger="click">
                        <More class="remote-block-toolbtn" @click.stop></More>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-if="remote.ssh_status === 0" :icon="SwitchButton" @click="handleConnect(remote)"> 连 接 </el-dropdown-item>
                                <el-dropdown-item v-if="remote.ssh_status === 1" :icon="TurnOff" @click="handleDisconnect(remote)"> 关 闭 </el-dropdown-item>
                                <el-dropdown-item :icon="Setting" @click="handleSetting(remote)"> 配 置 </el-dropdown-item>
                                <el-dropdown-item :icon="Delete" @click="handleDelete(remote)"> 删 除 </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
            <div class="remote-block-host">{{ remote.host }} : {{ remote.port }}</div>
        </div>
    </div>
</template>

<script setup>
import API from '@/js/api';
import { getCurrentInstance, onMounted, onUnmounted, ref } from 'vue';
import { SwitchButton, Setting, Delete, TurnOff } from '@element-plus/icons-vue';

const name = 'RemoteList';
const { proxy } = getCurrentInstance();
const emit = defineEmits(['remoteClick']);
defineExpose({ getRemoteList, updateSshStatus });

// 远程机器列表
let _remote_list = ref([]);
let _current_remote_id = ref(null);

// 获取远程连接
async function getRemoteList() {
    let result = await API.local.invoke('GetRemoteList');
    if (result.code == 0) {
        let remotes = result.msg.map((item) => {
            if (item.ssh_status == 1) {
                item.color = 'green';
            } else {
                item.color = '';
            }
            return item;
        });
        // console.log(remotes);
        _remote_list.value = remotes;

        // 读取当前的provider
        if (_current_remote_id.value == null) {
            let provider = API.getProvider();
            console.log('RemoteList onMounted! provider = ', provider);
            if (provider == 'Local') {
                _current_remote_id.value = 'local';
                emit('remoteClick', 'local');
            }
        }
    } else {
        ElMessage.error('获取远程服务器列表失败，错误信息:' + result.msg);
    }
}

async function onClickLocal() {
    // console.log('onClickLocal');
    _current_remote_id.value = 'local';
    emit('remoteClick', 'local');
}

async function onClickRemote(remote) {
    // console.log('onClickRemote remote = ', remote);
    _current_remote_id.value = remote.id;
    if (remote.ssh_status !== 1) {
        let result = await handleConnect(remote);
        // console.log('handleConnect result = ', result);
        if (!result) {
            return;
        } else {
            let loading = ElLoading.service({
                lock: true,
                text: '初始化远程环境...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            let result = await API.local.invoke('RemoteAppController', {
                remoteId: remote.id,
                operation: 'init'
            });
            console.log(result);
        }
    }
    emit('remoteClick', remote);
}

async function handleConnect(remote) {
    try {
        let result = await API.local.invoke('RemoteConnect', { remoteId: remote.id });
        console.log('RemoteConnect result = ', result);
        if (result.code == 0 || result.code == -2) {
            await getRemoteList();
            // await API.setProvider(`remote:${remote.id}`);
            return true;
        } else {
            ElMessage.error('连接远程服务器失败，错误信息:' + result.msg);
            return false;
        }
    } catch (error) {
        ElMessage.error('连接远程服务器失败，错误信息:' + error);
        return false;
    }
}

async function handleDisconnect(remote) {
    let result = await API.local.invoke('RemoteDisconnect', { remoteId: remote.id });
    // console.log(result);
    if (result.code == 0) {
        await getRemoteList();
        await API.setProvider('local');
    } else {
        ElMessage.error('断开远程服务器失败，错误信息:' + result.msg);
    }
}

function handleSetting(remote) {}

async function handleDelete(remote) {
    // console.log(`handleDelete remote = `, remote);
    let result = await API.local.invoke('DeleteRemote', { remoteId: remote.id });
    if (result.code == 0) {
        ElMessage.success('删除远程配置成功！');
        await getRemoteList();
    } else {
        ElMessage.error('删除远程配置失败，错误信息:' + result.msg);
    }
}

function updateSshStatus(remoteId) {
    console.log(`RemoteList updateSshStatus remoteId = `, remoteId);
    let remote = _remote_list.value.find((item) => {
        return item.id == remoteId;
    });
    // console.log(remote);
    if (remote) {
        remote.ssh_status = 0;
    }
}

onMounted(async () => {
    getRemoteList();
});

onUnmounted(() => {});
</script>

<style scoped>
.remote-list-wrapper {
    background-color: rgb(238, 238, 238);
    width: 100%;
    height: 100%;
}

.remote-list-title {
    font-size: 14px;
    font-weight: 800;
    height: 30px;
    color: rgb(88, 88, 88);
    padding: 5px 10px;
    background-color: rgb(223, 223, 223);
    box-sizing: border-box;
}

.remote-block {
    height: 60px;
    box-sizing: border-box;
    background-color: rgb(250, 250, 250);
    margin: 10px 10px 10px 5px;
    padding: 8px 10px;
    box-shadow: 0px 0px 2px 2px rgba(223, 223, 229, 0.5);
    overflow-wrap: break-word;
    word-break: break-word;
    border-left: 3px solid #5c5c5c;
    cursor: pointer;
}

.remote-block.status-1 {
    /* background-color: #f3faf4; */
    background-color: rgb(250, 250, 250);
    border-left: 5px solid #0fa002;
}

.remote-block.selected {
    background-color: #e0e7ff;
}

.remote-block-header {
    display: flex;
    justify-content: space-between;
}

.remote-block-title {
    font-size: 15px;
    font-weight: 600;
    color: black;
}

.remote-block-host {
    font-size: 14px;
    margin-top: 3px;
    color: rgb(123, 123, 123);
}

.remote-block-toolbar {
    display: flex;
}

.remote-block-toolbtn {
    width: 16px;
    height: 16px;
    color: black;
}

.remote-block-toolbtn:focus {
    outline: none;
}
</style>
